<template>
  <view class="order-detail">
    <view class="info-panel base-info">
      <text class="base-info-panel__title">
        基本信息
      </text>
      <up-cell-group :border="false">
        <up-cell title="联系人" :value="orderDetail.payName"/>
        <up-cell title="联系方式" :value="orderDetail.phone"/>
        <up-cell title="邮箱" :value="orderDetail.email"/>
        <up-cell v-if="orderDetail.type === '1'" title="身份证" :value="orderDetail.certNumber"/>
        <up-cell v-if="orderDetail.type === '0'" title="统一社会信用代码" :value="orderDetail.certNumber"/>
      </up-cell-group>
    </view>

    <view class="info-panel house-info">
      <text class="info-panel__title">
        房源信息
      </text>
      <up-cell-group :border="false">
        <up-cell title="户型类型" :value="orderDetail.houseType"/>
        <up-cell title="户号" :value="orderDetail.accountNumber"/>
        <up-cell title="选配设施" :value="`${orderDetail.chooseFacility}`"/>
        <up-cell title="设施租金" :value="`${orderDetail.facilityRent || 0}元`"/>
        <up-cell title="其他金额" :value="`${orderDetail.otherMoney	}元`"/>
        <up-cell title="押金" :value="`${orderDetail.cashPledge || 0} 元`"/>
        <up-cell title="预订金" :value="`${orderDetail.reservationDeposit || 0} 元`"/>
        <up-cell title="期数" :value="`${orderDetail.paymentMethod} 期`"/>
        <up-cell title="房屋租金" :value="`${orderDetail.houseRent} 元/期`"/>
        <up-cell title="实付金额" :value="`${orderDetail.allAmount} 元`"/>
      </up-cell-group>
    </view>
    <view class="info-panel refuse-info" v-if="refusedStatus.includes(orderDetail.payStatus)">
      <text class="info-panel__title" style="color:red">
        审核不通过原因
      </text>
      <view class="info-panel__text">
        {{ orderDetail?.approvalOpinion }}
      </view>
    </view>
    <view class="fixed-btn" v-if="showPayBtnStatus.includes(orderDetail.payStatus)">
      <up-button
          class="fixed-btn-pay"
          shape="circle"
          text="去支付"
          color="linear-gradient(to right, #FF934C, #FC686F)"
          @tap="handlePayBtnClick"
      />
    </view>

    <view class="popup-pay">
      <up-popup
          :show="payPopupDisabled"
          closeOnClickOverlay
          @close="handlePayPopupClose"
      >
        <view class="popup-pay__title">
          收银台
        </view>
        <view class="popup-pay__desc">
          <view class="popup-pay__desc-detail">
            <text class="popup-pay__desc-detail-label">
              应付金额
            </text>
            <text class="popup-pay__desc-detail-value">
              ¥ {{ orderDetail.allAmount }}元
            </text>
          </view>
        </view>
        <up-cell-group :border="false">
          <up-cell v-for="(item,idx) in payWayList" :key="idx">
            <template #title>
              <view class="u-slot-title">
                <image class="pay-way__img" :src="item.payWayPrefixIconUrl"/>
              </view>
              <view class="pay-way__name">
                <text class="pay-way__name-title">{{ item.payWayName }}</text>
                <text class="pay-way__name-desc">{{ item.desc }}</text>
              </view>
            </template>
            <template #value>
              <image
                  v-if="item.isChecked"
                  class="pay-way__img is-checked"
                  :src="isCheckedImgUrl"/>
              <image
                  v-else
                  class="pay-way__img"
                  :src="notCheckedImgUrl"
                  @tap="handleCheckedPayWay(item)"
              />
            </template>
          </up-cell>
        </up-cell-group>

        <view class="popup-pay__btn-group">
          <up-button
              class="btn__pay"
              shape="circle"
              :text="`立即支付¥ ${orderDetail.allAmount} 元`"
              :disabled="payWayList.every(way => !way.isChecked)"
              color="linear-gradient(to right, #FF934C, #FC686F)"
              @tap="handlePayForWithWayBtnClick"
          />
          <up-button
              class="btn__later-pay"
              plain
              shape="circle"
              text="稍后支付"
              type="warning"
              iconColor="linear-gradient(to right, #FF934C, #FC686F)"
              @tap="handleLaterPayBtnClick"
          />
        </view>
      </up-popup>
    </view>
  </view>
</template>
<script setup>
import {ref, inject} from 'vue'
import {onLoad} from "@dcloudio/uni-app";
import {getCurrentPagesTotal, getUrlParamsInH5, getUrlParamsInWeixin} from "@/utils/utils";
import {
  getOrderPayDataApi, userCancelPayApi,
} from "@/package_kuafu_apartment/pages/api/order";
import {customNav} from "@/utils/customNav";
const refusedStatus = ['3']
const showPayBtnStatus = ['0', '3', '5']
const orderDetail = ref({})
const payPopupDisabled = ref(false)
const handlePayBtnClick = () => {
  payPopupDisabled.value = true
}
const handlePayPopupClose = () => {
  payPopupDisabled.value = false
}
const imgUrlPrefix = inject('baseImgUrl')
const isCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103545102组 4@2x.png`
const notCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103688260椭圆 586 拷贝@2x.png`
const payWayList = ref([
  {
    payWayName: '微信支付',
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101755578weixin@2x.png`,
    desc: '亿万用户的选择，更快更安全',
    isChecked: false
  },
  {
    payWayName: '对公账号',
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101841808gongduigongzhuanzhang@2x.png`,
    desc: '以公开、透明的态度，为您提供优质的对公开户服务',
    isChecked: false
  }
])
const handleCheckedPayWay = item => {
  payWayList.value.forEach(way => {
    way.isChecked = way.payWayName === item.payWayName;
  })
}
const handleLaterPayBtnClick = () => {
  payPopupDisabled.value = false
  payWayList.value.forEach(way => {
    way.isChecked = false
  })
}
const handlePayForWithWayBtnClick = () => {
  if (payWayList.value.every(way => !way.isChecked)) return
  const way = payWayList.value.find(way => way.isChecked).payWayName
  switch (way) {
    case '微信支付':
      let payType = ''
      // #ifndef MP-WEIXIN
      payType = '1'
      // #endif

      // #ifdef MP-WEIXIN
      payType = '0'
      // #endif
      getOrderPayData(payType)
      break;
    case '对公账号':
      const orderId = orderDetail.value.reserveId
      const orderData = JSON.stringify([orderDetail.value])
      customNav(`public-transfer?orderId=${orderId}&price=${orderDetail.value.allAmount}&payName=房屋租金&orderData=${orderData}`)
      break
  }
}
const getOrderPayData = async (type) => {
  const params = {
    id: orderDetail.value.reserveId,
    payType: type
  }
  const res = await getOrderPayDataApi(params)
  const {code, data} = res
  if (code === 200) {
    // #ifndef MP-WEIXIN
    weChatAppPay(data)// 微信APP支付
    // #endif
    // #ifdef MP-WEIXIN
    toPay(data)//微信小程序支付
    // #endif
  }
}
const toPay = payData => {
  uni.requestPayment({
    provider: 'wxpay',
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log('success:' + JSON.stringify(res));
      uni.showToast({
        title: '支付成功',
        duration: 2000,
        success: () => {
          payPopupDisabled.value = false
        }
      })
    },
    fail: function (err) {
      userCancelPayApi(orderDetail.value.reserveId).then(res => {
        console.log('success' + JSON.stringify(res.data))
      })
      console.log('fail:' + JSON.stringify(err));
    }
  })
}
const weChatAppPay = payData => {
  let params = {
    partnerId: payData.partnerId,//商户号
    prepayId: payData.prepayId,//预支付交易会话ID
    nonceStr: payData.nonceStr,//随机字符串
    timeStamp: payData.timeStamp,//时间戳
    sign: payData.paySign//签名
  }
  window.mobile.jsCallPayWx(JSON.stringify(params))
}

onLoad(() => {

  /* #ifdef MP-WEIXIN */
  orderDetail.value = JSON.parse(getUrlParamsInWeixin()?.orderDetail)
  /* #endif */

  /* #ifndef MP-WEIXIN */
  orderDetail.value = JSON.parse(getUrlParamsInH5()?.orderDetail)
  /* #endif */
})
</script>
<style scoped lang=less>
@import "./style/lease-order-detail";
</style>
